//
//  UploadFileTool.m
//  HCJ
//
//  Created by 黄山锋 on 2017/12/5.
//  Copyright © 2017年 JuZhenBaoiMac. All rights reserved.
//

#import "UploadFileTool.h"

#import "AFNetworking.h"
#import "AFNetworkActivityIndicatorManager.h"
#import "QiniuUploadHelper.h"

static NSString *QiNiuBaseUrl = @"";

@implementation UploadFileTool



//上传单个文件
+ (void)uploadFileData:(NSData *)data fileName:(NSString *)fileName progress:(QNUpProgressHandler)progress success:(void (^)(NSString *url))success failure:(void (^)())failure {
    
    [UploadFileTool getQiniuUploadToken:^(NSString *token) {
        if (!data) {
            if (failure) {
                
                failure();
            }
            return;
        }
        
        QNUploadOption *opt = [[QNUploadOption alloc] initWithMime:nil
                                                   progressHandler:progress
                                                            params:nil
                                                          checkCrc:NO
                                                cancellationSignal:nil];
        QNUploadManager *uploadManager = [QNUploadManager sharedInstanceWithConfiguration:nil];
        
        [uploadManager putData:data
                           key:fileName
                         token:token
                      complete:^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
                          if (info.statusCode == 200 && resp) {
                              NSString *url= [NSString stringWithFormat:@"%@%@", QiNiuBaseUrl, resp[@"key"]];
                              if (success) {
                                  success(url);
                              }
                          }
                          else {
                              if (failure) {
                                  failure();
                              }
                          }
                      } option:opt];
        
    } failure:^{
        
    }];
}

//上传多个文件
+ (void)uploadFileDatas:(NSArray *)fileDataArray fileNameArr:(NSArray *)fileNameArr progress:(void (^)(CGFloat totalProgress))progress success:(void (^)(NSArray *urlArr))success failure:(void (^)())failure {
    
    NSMutableArray *array = [[NSMutableArray alloc] init];
    
    __block CGFloat totalProgress = 0.0f;
    __block CGFloat partProgress = 1.0f / [fileDataArray count];
    __block NSUInteger currentIndex = 0;
    
    QiniuUploadHelper *uploadHelper = [QiniuUploadHelper sharedUploadHelper];
    __weak typeof(uploadHelper) weakHelper = uploadHelper;
    
    uploadHelper.singleFailureBlock = ^() {
        failure();
        return;
    };
    uploadHelper.singleSuccessBlock  = ^(NSString *url) {
        [array addObject:url];
        totalProgress += partProgress;
        progress(totalProgress);
        currentIndex++;
        if ([array count] == [fileDataArray count]) {
            success([array copy]);
            return;
        }
        else {
            NSLog(@"---%ld",(unsigned long)currentIndex);
            if (currentIndex<fileDataArray.count) {
                [UploadFileTool uploadFileData:fileDataArray[currentIndex] fileName:fileNameArr[currentIndex] progress:nil success:weakHelper.singleSuccessBlock failure:weakHelper.singleFailureBlock];
            }
        }
    };
    [UploadFileTool uploadFileData:fileDataArray[0] fileName:fileNameArr[0] progress:nil success:weakHelper.singleSuccessBlock failure:weakHelper.singleFailureBlock];
}


//#error mark -- 必须设置获取七牛token服务器地址,然后获取token返回 --(确认设置后,删除此行)
//获取七牛的token
+ (void)getQiniuUploadToken:(void (^)(NSString *))success failure:(void (^)())failure {
    //获取七牛上传信息 （/api/file/getQiniuUploadInfo)
    [[DDNetworkManagerDate makeUrl_getQiniuUploadInfo_token:k_user_token] post_RequestFinshSuccess:^(id responseObject) {
        int stateCode = [responseObject intValueForKey:kRequsetCode default:-1];
        if (stateCode == 1) {
            NSDictionary *dic = [responseObject objectForKey:kRequsetDataKey];
            /*
             "data": {
             "url": "http://upload.qiniu.com/",      // 七牛提交网址
             "token": "FvndFHmyrPPPOOPBsNsYSDavK7ZAiXcserF9JCgj:VBVQxvXRK4ouZfXAW3AiFQt6WcI=:eyJzY29wZSI6Imh1aWNoZWppYW4iLCJkZWFkbGluZSI6MTUxMTE3Mjg2MywidXBIb3N0cyI6WyJodHRwOlwvXC91cC5xaW5pdS5jb20iLCJodHRwOlwvXC91cGxvYWQucWluaXUuY29tIiwiLUggdXAucWluaXUuY29tIGh0dHA6XC9cLzE4My4xMzEuNy4xOCJdfQ=="       //  七牛上传token
             "storageRoot":"http://xxx.xxx.com/"    // 存储网址，使用该网址与上传返回后的key值拼接访问上传文件
             }
             */
            NSString *QN_token = dic[@"token"];
//            NSString *storageRoot = dic[@"storageRoot"];
//            QiNiuBaseUrl = storageRoot;
            if (success) {
                success(QN_token);
            }
        }
    } failure:^(id errorObject) {
        if (failure) {
            failure();
        }
    }];
}




@end
